import { PowerParser } from '@/pages/Device/LowPower/utils/utils';
import type { ResponseData, ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import { rangePickerValueFomatter } from '@/utils/time';
import type { RequestData } from '@ant-design/pro-table';
import { message } from 'antd';
import moment from 'moment';
import { request } from 'umi';
import { xstatus, xtime } from '../utils/utils';
import type {
  DetailItem,
  DeviceConfigInfo,
  DeviceRegisterResponseData,
  DeviceResponseItem,
  OnlineStatus,
  QueryListParams,
  RegisterFormFields,
  TableListItem,
} from './data';

/**
 * 把选择框的在线状态转成对应的时间段的筛选条件
 * @param online
 */
function onLineStatusArr2TimeRange(online?: OnlineStatus) {
  if (!online) {
    return null;
  }

  const now = Date.now();
  const warnTime = now - 1000 * 60 * 60 * 5;
  const offlineTime = now - 1000 * 60 * 60 * 8;
  let [start, end]: [number | null, number | null] = [null, null];

  if (online === 'offline') {
    end = offlineTime;
  } else if (online === 'online') {
    start = warnTime;
  } else if (online === 'onlineAndWarn') {
    start = offlineTime;
  } else if (online === 'warnAndOffline') {
    end = warnTime;
  } else if (online === 'warn') {
    start = offlineTime;
    end = warnTime;
  }

  return [start ? moment(start) : null, end ? moment(end) : null];
}

/**
 * 获取设备列表
 * @param params
 */
export async function queryDeviceList(
  params: QueryListParams,
): Promise<RequestData<TableListItem>> {
  const [startLastedRefreshTime, endLastedRefreshTime] = params.lastedRefreshTime || [];
  const [onlineStartLastedRefreshTime, onlineEndLastedRefreshTime] =
    onLineStatusArr2TimeRange(params.online) || [];

  const res: ResponsePaginationData<DeviceResponseItem> = await request(`/device/list`, {
    params: {
      // type: params.type,
      page: params.page,
      pageSize: params.pageSize,
      deviceNo: params.deviceNo,
      status: params.status?.join(',') || '',
      serviceStatus: params.serviceStatus,
      spaceName: params.spaceName,
      startUpdateTime:
        startLastedRefreshTime?.format('YYYY-MM-DD HH:mm:00') ||
        onlineStartLastedRefreshTime?.format('YYYY-MM-DD HH:mm:00'),
      endUpdateTime:
        endLastedRefreshTime?.format('YYYY-MM-DD HH:mm:00') ||
        onlineEndLastedRefreshTime?.format('YYYY-MM-DD HH:mm:00'),
    },
  });
  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false, total: 0, data: [] };
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list.map((item) => ({
      ...item,
      status: xstatus.parse(item.status),
      statusList: xstatus.parses(item.statusBox),
      power: PowerParser.parseValue(item.power),
      serviceStatus: item.serviceStatus || 0,
      stateUpdateAt: xtime(item.stateUpdateAt || 0),
      updateAt: xtime(item.updateAt || 0),
      zone: item.zone ? { id: item.zone.id, name: item.zone.name } : undefined,
      space: item.spaceName || undefined,
    })),
  };
}

export async function queryLockerDetail(params: {
  deviceNo: string;
}): Promise<{ success: boolean; data?: DetailItem }> {
  const res = await request(`/device/get_device_detail_info`, {
    params,
  });

  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false };
  }

  return {
    success: true,
    data: {
      ...res.data,
      deviceNo: res.data.device.deviceNo,
      status: xstatus.parse(res.data.status.status),
      statusList: xstatus.parses(res.data.status.statusBox),
      statusBox: res.data.status.statusBox,
      power: PowerParser.parse(res.power),
      stateUpdateAt: xtime(res.data.status.stateUpdateAt),
      updateAt: xtime(res.data.status.updateAt),
      rssi: res.data.status.rtRssi,
      snr: res.data.status.rtSnr,
      batt: res.data.status.rtBatt,
      temp: res.data.status.rtTemp,
      sim: res.data.status.fwSim,
      imei: res.data.status.fwImei,
      zone: res.data.zone ? { id: res.data.zone?.id, name: res.data.zone?.name } : undefined,
      space: res.data.space
        ? { id: res.data.space.id, spaceName: res.data.space.spaceName }
        : undefined,
    },
  };
}

/**
 * 注册设备
 * 给超级客户使用的 用来将某一个设备注册到某一个客户上
 * TODO 传入的是一个设备列表 但是目前只有第一个设备可以被绑定
 * @param params
 */
export async function registerDevice(
  params: RegisterFormFields,
): Promise<DeviceRegisterResponseData> {
  const data: any = await request(`/device/register`, {
    method: 'POST',
    data: {
      deviceNo: Array.isArray(params.deviceNo) ? params.deviceNo[0] : params.deviceNo,
    },
  });
  return {
    message: data.message,
    data: data.data,
    code: data.code,
  };
}

// 注销设备
export async function unregisterDevice(params: { deviceNo: string; tenantId?: string }) {
  const res = await request('/device/unregister', {
    method: 'POST',
    data: {
      device_no: params.deviceNo,
      tenant_id: params.tenantId,
    },
  });
  if (res.code !== SUCCESS_CODE) {
    message.error(res.message);
    return res;
  }
  return res;
}

export async function transferDevice(params: { deviceNo: string }): Promise<ResponseData<any>> {
  return request(`/device/${params.deviceNo}/transfer`, {
    method: 'PATCH',
    data: { deviceNo: params.deviceNo },
  });
}

// 获取设备电量
export async function queryDevicePower(params: {
  deviceNo: string;
  rangePickerValue: [moment.Moment, moment.Moment];
}) {
  const filter = rangePickerValueFomatter(params.rangePickerValue).map((t: moment.MomentInput) =>
    moment(t).format('YYYY-MM-DD HH:mm:ss'),
  );
  const res = await request(`/data/statistics/battery/${params.deviceNo}`, {
    params: {
      startDate: filter[0],
      endDate: moment(filter[1]).add(1, 'seconds').format('YYYY-MM-DD HH:mm:ss'),
      unit: 'day',
    },
  });
  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false };
  }
  return { allOut: res.data.points };
}

export async function getLockerConfigInfo(params: { id: string }) {
  const res = await request(`/device/${params.id}/config`);
  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false };
  }
  return res;
}

export async function updateLockerConfigInfo(params: { config: DeviceConfigInfo; id: string }) {
  console.log(params.config);
  const res = await request(`/device/${params.id}/config`, {
    nethod: 'PUT',
    data: params.config,
  });
  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false };
  }
  return res;
}
